package org.whb.pet.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.whb.basic.util.AjaxResult;
import org.whb.basic.util.LoginContext;
import org.whb.basic.util.PageList;
import org.whb.pet.domain.Pet;
import org.whb.pet.query.PetQuery;
import org.whb.pet.service.IPetService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;


    @PostMapping
    public PageList<Pet> queryPage(@RequestBody PetQuery query, HttpServletRequest request){
        return petService.queryPage(query);
    }

    /**
     * 宠物上架
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody List<Long> ids){
        try {
            petService.onSale(ids);
            return new AjaxResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙，请稍后再试！！！");
        }
    }

    /**
     * 宠物上架
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            petService.offSale(ids);
            return new AjaxResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙，请稍后再试！！！");
        }
    }

    @GetMapping("{id}")
    public Pet queryById(@PathVariable Long id){
        return petService.queryByDetail(id);
    }

    @GetMapping("/adopt/{id}")
    public AjaxResult adopt(@PathVariable Long id,HttpServletRequest request){
        try {
            petService.adopt(id, LoginContext.getLogininfo(request));
            return new AjaxResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙，请稍后再试！！！");
        }
    }
}
